﻿import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;

public class TestCpu
{
    public static void main(String[] args) {
    ThreadMXBean newBean = ManagementFactory.getThreadMXBean();
    if (!newBean.isCurrentThreadCpuTimeSupported()) {
        System.out.println("CPU Usage monitoring is not avaliable!");
    } else {
        newBean.setThreadCpuTimeEnabled(true);
    }
 
    // The order of these two calls matters
    long start = System.nanoTime();
    long base_cpu = newBean.getCurrentThreadUserTime();
 
    for (int i = 0; i <  100; i++) {
        for (int j = 0; j < 1000000; j++) {
        Math.sin(j);
        }
 
        // The order of these two calls matters
        long cpu = newBean.getCurrentThreadUserTime();
        long time = System.nanoTime();
 
        System.out.println(i + " load: " +
                   (cpu - base_cpu) * 100.0 / (time - start));
    }
    
    }
}
